package one.stand.zuul.util;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.chatbot.SendResult;
import com.dingtalk.chatbot.message.MarkdownMessage;
import com.dingtalk.chatbot.message.Message;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import one.stand.util.HttpUtil2;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
public class DingTalkMsgClient {
    private static final String DEFAULT_CHATBOT_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=9c5e4bbfe25644af03f82edd452edc7269062b6ffbd98b9e4ab6408610c9ab11";

    public void send(String chatbotWebhook, String title, String content) {
        MarkdownMessage message = new MarkdownMessage();
        message.setTitle(title);

        message.add(MarkdownMessage.getBoldText(content));
        message.add("\n\n");
        sendMsg(chatbotWebhook, message);
    }

    public void sendError(String chatbotWebhook, ErrorMsgTemplate msgTemplate) {
        MarkdownMessage message = new MarkdownMessage();
        message.setTitle("错误通知");

        String exceptionMsg = getMessage(msgTemplate.getThrowable());
        String title = message.getTitle() + ":" + StringUtils.defaultIfBlank(msgTemplate.getMessage(), exceptionMsg);
        message.add(MarkdownMessage.getHeaderText(1, title));

        List<String> list = Lists.newArrayList();
        list.add("[Time] " + msgTemplate.getTime());
        list.add("[Host] " + msgTemplate.getApplication() + "(" + msgTemplate.getHost() + "-" + msgTemplate.getThreadName() + ")");
        list.add("[Url ] " + msgTemplate.getUrl());
        if (StringUtils.isNoneBlank(msgTemplate.getTraceId())) {
            list.add("[Trace] " + msgTemplate.getTraceId());
        }
        list.add("[User] " + msgTemplate.getUser() + "(" + msgTemplate.getUserId() + ")");
        list.add("[Detail] " + msgTemplate.getMessage());
        list.add("[Exception] " + exceptionMsg);
        message.add(MarkdownMessage.getUnorderListText(list));
        message.add("\n\n");

        sendMsg(chatbotWebhook, message);
    }

    public void sendMsg(String chatbotWebhook, Message message) {
        try {
            String webhook = Optional.ofNullable(chatbotWebhook).orElse(DEFAULT_CHATBOT_WEBHOOK);
            SendResult result = send(webhook, message);
            log.debug("ding: {}", result);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public SendResult send(String webhook, Message message) throws IOException {
        String responseStr = HttpUtil2.post(webhook, message.toJsonString());
        SendResult sendResult = new SendResult();
        JSONObject obj = JSONObject.parseObject(responseStr);
        Integer errcode = obj.getInteger("errcode");
        sendResult.setErrorCode(errcode);
        sendResult.setErrorMsg(obj.getString("errmsg"));
        sendResult.setIsSuccess(errcode.equals(0));
        return sendResult;
    }

    private String getMessage(Throwable e) {
        if (Objects.isNull(e)) return StringUtils.EMPTY;
        String msg = null;
        if (e instanceof UndeclaredThrowableException) {
            Throwable targetEx = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            if (targetEx != null) {
                msg = targetEx.getMessage();
            }
        } else {
            msg = e.getMessage();
        }
        return msg;
    }
}
